package com.sky.filter;


import com.alibaba.fastjson.JSONObject;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.utils.JwtUtil;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class DemoFilter implements Filter {
    private JwtProperties jwtProperties;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
//        log.info("init 初始化方法执行了：{ }");
        System.out.println("init 初始化方法执行了");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("doFilter 放行前~~~~~~~~~~~~~~~~~");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletRequest;

        String url = req.getRequestURI().toString();
        log.info("请求url:{}", url);

        if (url.contains("login")) {
            log.info("登录操作，放行");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        String jwt = req.getHeader("token");
//        String secretKey = req.getSe

        if (StringUtils.hasLength(jwt)) {
            log.info("请求头token为空，未返回登录信息");
            Result error = Result.error("NOT_LOGIN");
            // 手动装换
            String notLogin = JSONObject.toJSONString(error);
            res.getWriter().write(notLogin);
            return;
        }
        try {
//            JwtUtil.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败");
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            res.getWriter().write(notLogin);
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("doFilter 放行后~~~~~~~~~~~~~~~~~");
    }

    @Override
    public void destroy() {
        System.out.println("destroy 方法执行了");
    }
}
